<template>
    <div class="manage-management">
        <div style="display: flex;justify-content: space-between;" fit>
            <!-- 添加管理员信息 -->
            <el-button type="primary" @click="addManage">添加管理员</el-button>
            <!-- 搜索管理员信息 -->
            <div style="display: flex;">
                <el-input v-model="filterKeyword" placeholder="请输入用户名"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            </div>
        </div>
        <!-- 列表信息 -->
        <el-table :data="filteredManage" style="width: 100%;margin-top: 20px;" fit border>
            <el-table-column width="180" label="姓名" align="center">
                <template slot-scope="scope">
                    <p style="margin-left: 10px">{{ scope.row.managename }}</p>
                </template>
            </el-table-column>
            <el-table-column width="180" label="头像" align="center">
                <template slot-scope="scope">
                    <img v-if="scope.row.avaimg != ''" style="width:180px"
                        :src="require(`../../../trip-koa/public/manageavater/${scope.row.avaimg}`)" />
                    <p v-if="scope.row.avaimg == ''">个人信息未完善</p>
                </template>
            </el-table-column>

            <el-table-column width="180" label="电话" align="center">
                <template slot-scope="scope">
                    <p v-if="scope.row.phone != ''">{{ scope.row.phone }}</p>
                    <p v-if="scope.row.phone == ''">个人信息未完善</p>
                </template>
            </el-table-column>
            <el-table-column width="180" label="邮箱" align="center">
                <template slot-scope="scope">
                    <p v-if="scope.row.email != ''">{{ scope.row.email }}</p>
                    <p v-if="scope.row.email == ''">个人信息未完善</p>
                </template>
            </el-table-column>
            <el-table-column width="180" label="密码" align="center">
                <template slot-scope="scope">
                    <p>{{ scope.row.password }}</p>
                </template>
            </el-table-column>
            <el-table-column width="180" label="地址" align="center">
                <template slot-scope="scope">
                    <p v-if="scope.row.address != ''">{{ scope.row.address }}</p>
                    <p v-if="scope.row.address == ''">个人信息未完善</p>
                </template>
            </el-table-column>
            <el-table-column width="180" label="操作" align="center">
                <template slot-scope="{row}">
                    <el-button type="primary" size="small" @click="editManage(row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteManage(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @size-change="handlePageSizeChange" @current-change="handleCurrentPageChange"
            :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" :total="total"
            layout="total, sizes, prev, pager, next"></el-pagination>
        <!-- 弹出框 -->
        <el-dialog :visible.sync="dialogVisible" title="编辑用户">
            <el-form :model="editedManage" label-width="100px">
                <el-form-item label="头像">
                    <el-upload class="avatar-uploader" action="http://localhost:3001/subavater" :show-file-list="false"
                        :auto-upload="false" :on-change="handleChange" accept=".gif,.jpg,.jpeg,.png,.GIF,.JPG,.bmp"
                        name="img" :headers="headers">
                        <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
                        <img v-if="editedManage.avaimg != '' && imageUrl == ''" :src="editedManage.avaimg" class="avatar">
                        <i v-if="imageUrl == '' && editedManage.avaimg == ''" class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="editedManage.managename"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="editedManage.password"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="editedManage.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="editedManage.email"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="editedManage.address"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveManage">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            headers: { enctype: "multipart/form-data" },
            manage: [],// 获取的数据
            filteredManage: [],// 获取的数据
            filterKeyword: '',// 查找输入框的内容
            currentPage: 1, // 当前页
            pageSize: 10, // 当前页的条数
            dialogVisible: false, // 弹出框是否可视
            editedManage: {},// 修改用户信息的数据
            total: 0, // 总条数
            imageUrl: '',
            imageBase: "",
            imgUrl: ''
        }
    },
    methods: {
        // 获取管理员信息
        filterManage() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            this.$http
                .get('/getmanage')
                .then(res => {
                    this.manage = res.data;
                    this.filteredManage = res.data.slice(start, end)
                    this.total = res.data.length
                })
        },
        // 搜索管理员信息
        search() {
            const keyword = this.filterKeyword.trim().toLowerCase()
            if (keyword == '') {
                this.$message.error("请输入用户名")
            } else {
                const start = (this.currentPage - 1) * this.pageSize;
                const end = start + this.pageSize;
                this.$http
                    .post('/selmanage', { managename: keyword })
                    .then(res => {
                        if (res.data == undefined) {
                            this.filteredManage = res.data
                            this.$message.error(res.status)
                        } else {
                            this.filteredManage = res.data.slice(start, end)
                            this.total = res.data.length
                            this.$message.success(res.status)
                        }
                    })
            }
        },
        // 打开增加管理员信息表单
        addManage() {
            this.editedManage = { avaimg: '', managename: '', phone: '', email: '', address: '' }
            this.dialogVisible = true
        },
        // 打开编辑用户信息表单
        editManage(user) {
            console.log(user)
            if (user.avaimg == '') {
                this.editedManage = { ...user }
            } else {
                this.imgUrl = require(`../../../trip-koa/public/manageavater/${user.avaimg}`)
                this.editedManage = { ...user, avaimg: user.avaimg && require(`../../../trip-koa/public/manageavater/${user.avaimg}`) }
            }
            this.dialogVisible = true
        },
        // 提交管理员头像到服务器成功
        blobToBase64(blob) {
            return new Promise((resolve, reject) => {
                const fileReader = new FileReader();
                fileReader.onload = (e) => {
                    resolve(e.target.result)
                }
                fileReader.readAsDataURL(blob)
                fileReader.onerror = () => {
                    reject(new Error("文件流异常"))
                }
            })
        },
        handleChange(file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            console.log(this.imageUrl)
            this.blobToBase64(file.raw).then(res => {
                this.imageBase = res
            })
        },
        // 保存用户信息
        saveManage() {
            if (this.editedManage.managename.trim() === '') {
                this.$message.error('姓名不能为空')
                return
            }
            if (this.editedManage.password.trim() === '') {
                this.$message.error('密码不能为空')
                return
            }
            if (this.editedManage.phone.length !== 11) {
                this.$message.error("手机号位数错误")
                return
            }
            let mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
            if (!mailReg.test(this.editedManage.email.trim()) && this.editedManage.email.trim() !== '') {
                this.$message.error("邮箱格式错误，请重新输入")
                return
            }
            if (this.editedManage.hasOwnProperty('id')) {
                // 修改用户信息
                if (this.imageBase == "") {
                    // 未修改图片
                    this.editedManage.avaimg = this.imgUrl
                } else {
                    // 修改图片
                    this.editedManage.avaimg = this.imageBase
                    this.editedManage.img = this.imgUrl
                }
                this.$http
                    .post('/editmanage', this.editedManage)
                    .then(res => {
                        console.log(res.data)
                        window.localStorage.setItem("result", JSON.stringify(res.data))
                        this.$message.success(res.status)
                    })
            } else {
                // 增加用户信息
                this.editedManage.avaimg = this.imageBase
                this.$http
                    .post('/addmanage', this.editedManage)
                    .then(res => {
                        this.$message.success(res.status)
                    })
            }
            this.imageUrl = ''
            if (!this.filterKeyword) {
                this.filterManage()
            } else {
                this.search()
            }
            this.dialogVisible = false
        },
        // 删除用户信息
        deleteManage(manage) {
            this.$confirm(`确定要删除用户 ${manage.managename} 吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.$http
                    .post('/delmanage', manage)
                    .then(res => {
                        this.$message.success(res.status)
                        if (!this.filterKeyword) {
                            this.filterManage()
                        } else {
                            this.search()
                        }
                    })
            })
        },
        // 切换每页条数
        handlePageSizeChange(size) {
            this.pageSize = size
            this.currentPage = 1
            this.filterManage()
        },
        // 切换页码
        handleCurrentPageChange(page) {
            this.currentPage = page
            this.filterManage()
        },
    },
    mounted() {
        this.filterManage()
    },
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 45px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    /* text-align: center; */
}

.avatar {
    width: 90px;
    height: 90px;
    display: block;
}
</style>